import React,{Component} from 'react';
import { Form, Input, Button, Table, Select, Checkbox, Upload, message, Icon } from 'antd';
import { Link, history} from 'react-router-dom';
import './index.less';
import axios from 'axios';
import Bread from '../../common/Bread/index';
const {TextArea} = Input;
const FormItem = Form.Item;
const Option = Select.Option;
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';


class createOrganization extends React.Component {
	constructor(props){
		super(props)
		this.state = {
			getCode: '',
			oldMobile: '',
			checked: false,
			businesslicense: '',
			contactName: '',
			cardFront: '',
			cardBack: '',
			cardHand: '',
			cardFront_1: '',
			cardBack_1: '',
			cardHand_1: '',
			uploadArr: [],
			cardFrontArr: [],
			cardBackArr: [],
			cardHandArr: [],
			cardFrontArr_1: [],
			cardBackArr_1: [],
			cardHandArr_1: [],
		}
	}

	onChange = (e) => {
		this.setState({
		  checked: e.target.checked,
		  cardFrontArr_1: [],
		  cardBackArr_1: [],
		  cardHandArr_1: [],
		});
		this.props.form.setFieldsValue({
			legalPerson: '',
			cardFront_1: '',
			cardBack_1: '',
			cardHand_1: '',
		})
		// this.props.form.resetFields(['cardFront','cardBack','cardHand', 'phone', 'code', 'email', []])
	}
	handleSubmit = (e)=>{
		e.preventDefault();
		const _this = this;
		const Token = localStorage.getItem("token");
		const phone = this.state.oldMobile;
		this.props.form.validateFields((err, values) => {
			if(!err){
				var data = {
					orgName: values.orgName,
					englishName: values.englishName,
					orgAddress: values.orgAddress,
					businesslicense: _this.state.businesslicense,
					realname: _this.state.contactName,
					contactsFrontCard: _this.state.cardFront,
					contactsBackCard: _this.state.cardBack,
					contactsImgeCard: _this.state.cardHand,
					phone: phone,
					email: values.email,
					code: values.code,
					legalPerson: values.legalPerson,
					legalFrontCard: _this.state.cardFront_1,
					legalBackCard: _this.state.cardBack_1,
					legalImgeCard: _this.state.cardHand_1
				}
				var data_1 = {
					orgName: values.orgName,
					englishName: values.englishName,
					orgAddress: values.orgAddress,
					businesslicense: _this.state.businesslicense,
					realname: _this.state.contactName,
					contactsFrontCard: _this.state.cardFront,
					contactsBackCard: _this.state.cardBack,
					contactsImgeCard: _this.state.cardHand,
					phone: phone,
					email: values.email,
					code: values.code,
				}
				axios({
					method: 'get',
					url: '/api/customer/rest/checkMsg?mobile='+ data.phone +'&code='+ data.code,
					headers: {
						'Content-Type': 'application/json',
						Authorization:Token,
					}
				})
				.then(function(response){
					if(response.data.data == 'error') {
						message.warning('请输入正确的验证码');
					}else if(response.data.data == 'success'){
						axios({
							method: 'post',
							url: '/api/customer/org/approval/add',
							data: (_this.state.checked == true) ? data_1 : data,
							headers: {
								'Content-Type': 'application/json',
								Authorization:Token,
							}
						})
						.then(function (response) {
							if(response.data.code == '201'){
								message.warning(response.data.message);
							}else if(response.data.code == '202'){
								message.warning(response.data.message);
							}else if(response.data.code == '203'){
								message.warning(response.data.message);
							}else if(response.data.code == '204'){
								message.warning(response.data.message);
							}else if(response.data.code == '200'){
								message.success(response.data.message);
								_this.props.history.push('/accountService/Waitingexamine');
							}
						})
						.catch(function (error) {
							console.log(error);
						});
					}
				})
				
			}else {
				console.log('Received values of form: ', values);
			}
		})
	}

	handleCode =()=>{
		const _this = this;
		let sec = 60;
		const clickTime = new Date().getTime();
		localStorage.setItem("fillclickTime",clickTime);
		const mobile = this.state.oldMobile;
		const Token = localStorage.getItem("token");
		if(this.state.getCode !== '获取验证码'){
			return false;
		}
		axios({
			method: 'get',
			url: '/api/customer/rest/sendMsg?mobile='+ mobile,
			headers: {
				'Content-Type': 'application/json',
				Authorization:Token,
			}
		})
		.then(function(response){
			if(response.data.code == '201'){
				message.warning('请输入正确的手机号');
			}else if(response.data.code == '202'){
				message.warning('获取手机验证码失败');
			}else if(response.data.code == '200') {
				const timer = setInterval(function(){
					sec--;
					if(sec < 0){
						clearInterval(timer);
						_this.setState({
							getCode:  '获取验证码',
						})
						localStorage.setItem("fillclickTime","");
					}else {
						_this.setState({
							getCode:  sec + 's 后重新获取',
						})
					}
				},1000)
			}
		})
	}

	componentWillMount(){
		const _this = this;
		const nowDate = new Date().getTime();
		let sec = localStorage.getItem("fillclickTime");
		const currentTime = (nowDate - sec)/1000;
		let delta = Math.round(60 - currentTime);
		const timer = setInterval(function(){
			delta--;
			if(delta < 0){
				clearInterval(timer);
				_this.setState({
					getCode:  '获取验证码',
				})
			}else {
				_this.setState({
					getCode:  delta + 's 后重新获取',
				})
			}
		},1000)
		
		const Token = localStorage.getItem("token");
		axios({
		  method: 'get',
		  url: '/api/customer/user/getUser',
		  headers: {
		    'Content-Type': 'application/json',
		    Authorization:Token,
		  }
		})
		.then(function(response){
		  if(response.data.code == '200'){
		    _this.setState({
		        oldMobile: response.data.data.telPhone,
		        contactName: response.data.data.name
		    })
		  }
		})
		.catch(function(error){
		  message.error('获取手机号失败')
		})
	}

 	uploadImg = (Name,listArr)=>{
 		//上传文件
 		const Token = localStorage.getItem("token");
 		const _this = this;
 		const props = {
 		  listType: "picture",
 		  action: '/api/customer/org/upload',
 		  headers: {
 		    Authorization:Token
 		  },
 		  beforeUpload (file) {
 		    const rFilter = /^(image\/bmp|image\/gif|image\/jpeg|image\/png|image\/tiff|application\/pdf)$/i;
 		    const isLt10M = file.size / 1024 / 1024 < 10;
 		    // console.log(file)
 		    if (!rFilter.test(file.type)) {
 			  message.error('文件格式必须为图片或PDF!');
 			  setTimeout(() => {
 			  	_this.setState({
	 		  		[listArr]: [],
 		  	  	})
 		  	  	_this.props.form.setFieldsValue({
					[Name]: '',
				})
 			  },1000)
 		      return false
 		    }
 		    // console.log(file.size)
 		    if (!isLt10M) {
 		      message.error('图片大小不能超过10M!');
 		      setTimeout(() => {
 			  	_this.setState({
	 		  		[listArr]: [],
 		  	  	})
 		  	  	_this.props.form.setFieldsValue({
					[Name]: '',
				})
 			  },1000)
 		      return false
 		    }
 		    return rFilter && isLt10M;
 		  },
 		  onChange(info) {
 		    if (info.file.status === 'done') {
 		    	_this.setState({
 		    		[Name]: info.file.response.data.url
 		    	})
 		    	message.success('上传成功！');
 		    } else if (info.file.status === 'error') {
				message.error('上传失败！');
				setTimeout(() => {
	 			  	_this.setState({
	 		  			[listArr]: [],
	 		  	  	})
	 		  	  	_this.props.form.setFieldsValue({
						[Name]: '',
					})
 			  	},1000)
 		    }
 		    _this.setState({
 		    	[listArr]: [info.file]
 		    })
 		  },
 		  onRemove(info) {
	  		_this.props.form.setFieldsValue({
	  			[Name]: ''
	  		})
 		  	_this.setState({
 		  		[listArr]: [],
 		  		[Name]: '',
 		  	})
 		  },
 		};
 		return props;
 	}

	render(){
		const { getFieldDecorator } = this.props.form;
		const disabled = this.state.getCode !== '获取验证码' ? "disabled" : "";
		const checkedClass = (this.state.checked == true) ? 'legalPersonInfo hide' : 'legalPersonInfo';
		const formItemLayout = {
			    labelCol: { span: 5 },
			    wrapperCol: { span: 11 },
		    };
		return(
			<div style={{paddingTop: '1px'}}>
				<Bread bread={['组织管理',['组织管理','accountService'],['新建一个组织','accountService/Fillimformation']]}/>
				<div className="subTopBox">
					<div className="subTopBox-hd">
						<div className="hd-title">
							<span className="step active">
								<i>1</i> 
							同意协议</span>
							<em className="line active"></em>
							<span className="step active">
								<i>2</i>
							填写资料</span>
							<em className="line"></em>
							<span className="step">
								<i>3</i>
							等待审核</span>
						</div>
					</div>
					<div className="companyInfo">
						<Form onSubmit={this.handleSubmit}>
							<div className="companyInfo-ft">
								<h3 className="subTitle">机构信息审核</h3>
								<h4 className="orgInfo">组织信息</h4>
								<FormItem label="组织名称" {...formItemLayout}>	
									{getFieldDecorator('orgName',{
										rules: [{required: true, message: '请输入组织名称'}]
									})(
										<Input placeholder="请输入组织名称" />
									)}
								</FormItem>
								<FormItem label="组织英文名称" {...formItemLayout}>	
									{getFieldDecorator('englishName',{
										rules: [{required: true, message: '请输入不包含数字的英文名称', pattern: /^[a-zA-Z]+$/}]
									})(
										<Input placeholder="请输入不包含数字的英文名称" />
									)}
								</FormItem>
								<FormItem label="机构办公地址" {...formItemLayout}>	
									{getFieldDecorator('orgAddress',{
										rules: [{required: true, message: '请输入机构办公地址'}]
									})(
										<Input placeholder="请输入机构办公地址" />
									)}
								</FormItem>
								<FormItem label="营业执照上传" {...formItemLayout}>	
									{getFieldDecorator('businesslicense',{
										rules: [{required: true, message: '请上传营业执照'}]
									})(
										<div className="uploadBox">
											<Upload {...this.uploadImg('businesslicense','uploadArr')} fileList = {this.state.uploadArr}>
									    	    <Button type="primary" className="uploadBtn">上传文件</Button>
									    	</Upload>
									    	<span className="noticeTips">注：营业执照</span>
								    	</div>
									)}
								</FormItem>
								<div className="checkInfo">	
									<div className='contactInfo'>
										<h4 className="orgInfo">联系人信息</h4>
										<FormItem label="联系人姓名" {...formItemLayout}>	
											<Input value={this.state.contactName} disabled />
										</FormItem>
										<FormItem label="身份证正面" {...formItemLayout}>	
											{getFieldDecorator('cardFront',{
												rules: [{required: true, message: '请上传身份证正面照'}]
											})(
												<div className="uploadBox">	
													<Upload {...this.uploadImg('cardFront','cardFrontArr')} fileList = {this.state.cardFrontArr}>
											    	    <Button type="primary" className="uploadBtn">上传文件</Button>
											    	</Upload>
										    	</div>
											)}
										</FormItem>
										<FormItem label="身份证反面" {...formItemLayout}>	
											{getFieldDecorator('cardBack',{
												rules: [{required: true, message: '请上传身份证反面照'}]
											})(
												<div className="uploadBox">	
													<Upload {...this.uploadImg('cardBack','cardBackArr')} fileList = {this.state.cardBackArr}>
											    	    <Button type="primary" className="uploadBtn">上传文件</Button>
											    	</Upload>
										    	</div>
											)}
										</FormItem>
										<FormItem label="手持身份证" {...formItemLayout}>	
											{getFieldDecorator('cardHand',{
												rules: [{required: true, message: '请上传手持身份证照'}]
											})(
												<div className="uploadBox">	
													<Upload {...this.uploadImg('cardHand','cardHandArr')} fileList = {this.state.cardHandArr}>
											    	    <Button type="primary" className="uploadBtn">上传文件</Button>
											    	</Upload>
										    	</div>
											)}
										</FormItem>
										<FormItem className="namePhone" label="预留手机号码" {...formItemLayout}>
										    {getFieldDecorator('phone', {
						                        rules: [{required: false, message: '请输入预留手机号码'}],
						                    })(
						                    	<div>
							                        <Input className="phoneText" disabled value={this.state.oldMobile} />
							                        <Button
											            className="yzmBtn"
											            type= "primary"
											            size="small"
											            // disabled
											            disabled={disabled}
											            onClick = {this.handleCode}
											          >
											          {this.state.getCode}
										        </Button>
							                    </div>    
						                    )}
										</FormItem>
										<FormItem label="短信验证码" {...formItemLayout}>	
											{getFieldDecorator('code',{
												rules: [{required: true, message: '请输入短信验证码，仅限数字', pattern: /^[0-9]+$/}]
											})(
												<Input type="text" placeholder="请输入短信验证码，仅限数字" maxLength={8} />
											)}
										</FormItem>
										<FormItem label="邮箱账号" {...formItemLayout}>	
											{getFieldDecorator('email',{
												rules: [{required: true, message: '请输入邮箱账号'}]
											})(
												<Input placeholder="请输入邮箱账号" />
											)}
										</FormItem>
									</div>
								<Checkbox
								      checked={this.state.checked}
								      onChange={this.onChange}>
								</Checkbox> 法人和联系人是否同人</div>
								<div className={checkedClass}>
									<h4 className="orgInfo">法人信息</h4>
									<FormItem label="法人姓名" {...formItemLayout}>	
										{getFieldDecorator('legalPerson',{
											rules: [{required: (this.state.checked == true) ? false : true, message: '请输入法人姓名'}]
										})(
											<Input placeholder="请输入法人姓名" />
										)}
									</FormItem>
									<FormItem label="身份证正面" {...formItemLayout}>	
										{getFieldDecorator('cardFront_1',{
											rules: [{required: (this.state.checked == true) ? false : true, message: '请上传身份证正面照'}]
										})(
											<div className="uploadBox">	
												<Upload {...this.uploadImg('cardFront_1','cardFrontArr_1')} fileList = {this.state.cardFrontArr_1}>
										    	    <Button type="primary" className="uploadBtn">上传文件</Button>
										    	</Upload>
									    	</div>
										)}
									</FormItem>
									<FormItem label="身份证反面" {...formItemLayout}>	
										{getFieldDecorator('cardBack_1',{
											rules: [{required: (this.state.checked == true) ? false : true, message: '请上传身份证反面照'}]
										})(
											<div className="uploadBox">	
												<Upload {...this.uploadImg('cardBack_1','cardBackArr_1')} fileList = {this.state.cardBackArr_1}>
										    	    <Button type="primary" className="uploadBtn">上传文件</Button>
										    	</Upload>
									    	</div>
										)}
									</FormItem>
									<FormItem label="手持身份证" {...formItemLayout}>	
										{getFieldDecorator('cardHand_1',{
											rules: [{required: (this.state.checked == true) ? false : true, message: '请上传手持身份证照'}]
										})(
											<div className="uploadBox">	
												<Upload {...this.uploadImg('cardHand_1','cardHandArr_1')} fileList = {this.state.cardHandArr_1}>
										    	    <Button type="primary" className="uploadBtn">上传文件</Button>
										    	</Upload>
									    	</div>
										)}
									</FormItem>
								</div>	
							</div>
							<FormItem className="submitBtns" label=" " {...formItemLayout}>	
								<div>
									<Link to="/accountService/CreateOrganization"><Button type="default" className="prevBtn">上一步</Button></Link>
									<Button type="primary" htmlType="submit" className="joinBtn">提交审核</Button>
								</div>
							</FormItem>
							
						</Form>	
					</div>
				</div>
			</div>	
			)
	}
}

const CreateOrganization = Form.create()(createOrganization);
export default CreateOrganization

